package com.cuicui.mall.service;

import com.cuicui.mall.dao.UserDataMapper;
import com.cuicui.mall.entity.UserData;
import com.cuicui.mall.entity.UserDataExample;
import com.cuicui.mall.utils.CommonResponse;
import com.cuicui.mall.utils.JwtUtils;
import com.cuicui.mall.utils.MD5;
import com.cuicui.mall.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class AuthService {
    @Autowired
    private UserDataMapper userDao;

    public CommonResponse login (LoginVO loginVO) {
        MD5 md5 = new MD5();
        loginVO.setPassWrod(md5.encode(loginVO.getPassWrod()));
        UserDataExample selectUserExample = new UserDataExample();
        UserDataExample.Criteria criteria = selectUserExample.createCriteria();
        criteria.andNameEqualTo(loginVO.getUserName());
        criteria.andPwdEqualTo(loginVO.getPassWrod());
        List<UserData> userlist = userDao.selectByExample(selectUserExample);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-DD hh:mm");
        String loginDateStr = simpleDateFormat.format(new Date());
        if(CollectionUtils.isEmpty(userlist)){
            return CommonResponse.front_error("用户名或密码错误!");
        }
        return  CommonResponse.success(JwtUtils.sign(loginVO.getUserName(), loginDateStr));
    }
}
